import SwiftUI
import AVFoundation

struct ProfessionalCameraView: View {
    @StateObject private var cameraManager = CameraManager()
    @State private var showingFilterView = false
    @State private var capturedImage: UIImage?
    @State private var selectedFilterIndex = 0
    @State private var isFlashOn = false
    @State private var showingSettings = false
    @Environment(\.dismiss) private var dismiss
    
    private let filterPreviews = FilterEngine.FilterType.allCases
    
    var body: some View {
        ZStack {
            // Camera preview background
            Color.black.ignoresSafeArea()
            
            // Camera preview
            CameraPreview(cameraManager: cameraManager)
                .ignoresSafeArea()
                .clipped()
            
            // UI overlay
            VStack(spacing: 0) {
                topControlBar
                
                Spacer()
                
                filterSelectionBar
                
                bottomControlBar
            }
        }
        .navigationBarHidden(true)
        .onAppear {
            cameraManager.requestPermission()
        }
        .fullScreenCover(isPresented: $showingFilterView) {
            if let image = capturedImage {
                ProfessionalEditView(image: image)
            }
        }
    }
    
    // MARK: - Top Control Bar
    private var topControlBar: some View {
        HStack {
            // Close button
            Button(action: { dismiss() }) {
                Image(systemName: "xmark")
                    .font(.system(size: 18, weight: .medium))
                    .foregroundColor(.white)
                    .frame(width: StyleConstants.Layout.toolButtonSize, height: StyleConstants.Layout.toolButtonSize)
                    .background(StyleConstants.Colors.cameraOverlay)
                    .clipShape(Circle())
                    .overlay(
                        Circle()
                            .stroke(Color.white.opacity(0.2), lineWidth: 0.5)
                    )
            }
            
            Spacer()
            
            // Camera settings
            HStack(spacing: StyleConstants.Spacing.md) {
                // Flash toggle
                Button(action: { 
                    isFlashOn.toggle()
                    // TODO: Implement flash functionality
                }) {
                    Image(systemName: isFlashOn ? "bolt.fill" : "bolt.slash")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(isFlashOn ? .yellow : .white)
                        .frame(width: StyleConstants.Layout.toolButtonSize, height: StyleConstants.Layout.toolButtonSize)
                        .background(StyleConstants.Colors.cameraOverlay)
                        .clipShape(Circle())
                        .overlay(
                            Circle()
                                .stroke(Color.white.opacity(0.2), lineWidth: 0.5)
                        )
                }
                
                // Settings button
                Button(action: { showingSettings = true }) {
                    Image(systemName: "slider.horizontal.3")
                        .font(.system(size: 16, weight: .medium))
                        .foregroundColor(.white)
                        .frame(width: StyleConstants.Layout.toolButtonSize, height: StyleConstants.Layout.toolButtonSize)
                        .background(StyleConstants.Colors.cameraOverlay)
                        .clipShape(Circle())
                        .overlay(
                            Circle()
                                .stroke(Color.white.opacity(0.2), lineWidth: 0.5)
                        )
                }
            }
        }
        .padding(.horizontal, StyleConstants.Spacing.lg)
        .padding(.top, StyleConstants.Spacing.md)
    }
    
    // MARK: - Filter Selection Bar
    private var filterSelectionBar: some View {
        VStack(spacing: StyleConstants.Spacing.sm) {
            // Filter name
            Text(filterPreviews[selectedFilterIndex].displayName)
                .font(StyleConstants.Typography.caption)
                .foregroundColor(.white)
                .padding(.horizontal, StyleConstants.Spacing.md)
                .padding(.vertical, StyleConstants.Spacing.xs)
                .background(StyleConstants.Colors.cameraOverlay)
                .cornerRadius(StyleConstants.Layout.smallCornerRadius)
            
            // Filter thumbnails
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: StyleConstants.Spacing.md) {
                    ForEach(Array(filterPreviews.enumerated()), id: \.offset) { index, filterType in
                        FilterThumbnailView(
                            filterType: filterType,
                            isSelected: index == selectedFilterIndex
                        ) {
                            withAnimation(StyleConstants.Animation.quick) {
                                selectedFilterIndex = index
                            }
                        }
                    }
                }
                .padding(.horizontal, StyleConstants.Spacing.lg)
            }
        }
        .padding(.bottom, StyleConstants.Spacing.md)
    }
    
    // MARK: - Bottom Control Bar
    private var bottomControlBar: some View {
        HStack {
            // Photo library button
            Button(action: {
                // TODO: Open photo library
            }) {
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                    .fill(StyleConstants.Colors.cameraOverlay)
                    .frame(width: StyleConstants.Layout.toolButtonSize, height: StyleConstants.Layout.toolButtonSize)
                    .overlay(
                        Image(systemName: "photo.on.rectangle")
                            .font(.system(size: 16, weight: .medium))
                            .foregroundColor(.white)
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                            .stroke(Color.white.opacity(0.2), lineWidth: 0.5)
                    )
            }
            
            Spacer()
            
            // Capture button
            Button(action: {
                capturePhoto()
            }) {
                ZStack {
                    // Outer ring
                    Circle()
                        .stroke(Color.white.opacity(0.8), lineWidth: StyleConstants.Layout.captureButtonBorderWidth)
                        .frame(width: StyleConstants.Layout.captureButtonSize, height: StyleConstants.Layout.captureButtonSize)
                    
                    // Inner circle
                    Circle()
                        .fill(Color.white)
                        .frame(width: StyleConstants.Layout.captureButtonSize - 16, height: StyleConstants.Layout.captureButtonSize - 16)
                        .scaleEffect(1.0)
                        .shadow(color: .black.opacity(0.3), radius: 4, x: 0, y: 2)
                }
            }
            .scaleEffect(1.0)
            .animation(StyleConstants.Animation.springBouncy, value: selectedFilterIndex)
            
            Spacer()
            
            // Camera switch button
            Button(action: {
                // TODO: Switch camera
            }) {
                Image(systemName: "camera.rotate")
                    .font(.system(size: 18, weight: .medium))
                    .foregroundColor(.white)
                    .frame(width: StyleConstants.Layout.toolButtonSize, height: StyleConstants.Layout.toolButtonSize)
                    .background(StyleConstants.Colors.cameraOverlay)
                    .clipShape(Circle())
                    .overlay(
                        Circle()
                            .stroke(Color.white.opacity(0.2), lineWidth: 0.5)
                    )
            }
        }
        .padding(.horizontal, StyleConstants.Spacing.xl)
        .padding(.bottom, StyleConstants.Spacing.xl)
    }
    
    // MARK: - Actions
    private func capturePhoto() {
        // Add haptic feedback
        let impactFeedback = UIImpactFeedbackGenerator(style: .medium)
        impactFeedback.impactOccurred()
        
        cameraManager.capturePhoto { image in
            capturedImage = image
            showingFilterView = true
        }
    }
}

// MARK: - Filter Thumbnail View
struct FilterThumbnailView: View {
    let filterType: FilterEngine.FilterType
    let isSelected: Bool
    let onTap: () -> Void
    
    var body: some View {
        VStack(spacing: StyleConstants.Spacing.xs) {
            // Thumbnail preview
            ZStack {
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                    .fill(StyleConstants.Colors.cameraOverlay)
                    .frame(width: StyleConstants.Layout.filterThumbnailSize, height: StyleConstants.Layout.filterThumbnailSize)
                
                // Placeholder for actual filter preview
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius - 2)
                    .fill(
                        LinearGradient(
                            gradient: gradientForFilter(filterType),
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: StyleConstants.Layout.filterThumbnailSize - 4, height: StyleConstants.Layout.filterThumbnailSize - 4)
            }
            .overlay(
                RoundedRectangle(cornerRadius: StyleConstants.Layout.smallCornerRadius)
                    .stroke(
                        isSelected ? Color.white : Color.white.opacity(0.2),
                        lineWidth: isSelected ? 2 : 0.5
                    )
            )
            .scaleEffect(isSelected ? 1.1 : 1.0)
            .animation(StyleConstants.Animation.quick, value: isSelected)
            
            // Filter name
            Text(filterType.displayName)
                .font(StyleConstants.Typography.caption2)
                .foregroundColor(isSelected ? .white : .white.opacity(0.7))
                .fontWeight(isSelected ? .medium : .regular)
                .lineLimit(1)
                .frame(width: StyleConstants.Layout.filterThumbnailSize)
        }
        .onTapGesture {
            onTap()
        }
    }
    
    private func gradientForFilter(_ filterType: FilterEngine.FilterType) -> Gradient {
        switch filterType {
        case .original:
            return Gradient(colors: [Color.gray.opacity(0.6), Color.gray.opacity(0.3)])
        case .warm:
            return Gradient(colors: [Color.orange.opacity(0.6), Color.red.opacity(0.4)])
        case .fresh:
            return Gradient(colors: [Color.green.opacity(0.6), Color.blue.opacity(0.4)])
        case .elegant:
            return Gradient(colors: [Color.purple.opacity(0.6), Color.gray.opacity(0.4)])
        }
    }
}

#Preview {
    ProfessionalCameraView()
        .preferredColorScheme(.dark)
}